3.3.2 使用多个处理器

在大部分情况下,我们并不希望像代码清单3-6那样,使用一个处理器去处理所有请求,而是希望使用多个处理器去处理不同的 URL。为了做到这一点,我们不再在 Server 结构的 Handler 字段中指定处理器,而是让服务器使用默认的 DefaultServeMux 作为处理器,然后通过 http.Handle 函数将处理器绑定至 DefaultServeMux 。需要注意的是,虽然 Handle 函数来源于 http 包,但它实际上是 ServeMux 结构的方法:这些函数是为了操作便利而创建的函数,调用它们等同于调用 DefaultServeMux 的某个方法。比如说,调用 http.Handle 实际上就是在调用 DefaultServeMuxHandle 方法。

在代码清单3-7中,程序创建了两个处理器,并将它们与各自的URL进行了绑定。现在,访问地址http://localhost:8080/hello将会看到“Hello!”,而访问地http://localhost:8080/world则会看到“World!”。

代码清单3-7 使用多个处理器对请求进行处理

package main
import (
  "fmt"
  "net/http"
)
type HelloHandler struct{}
func (h *HelloHandler) ServeHTTP (w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Hello!")
}
type WorldHandler struct{}
func (h *WorldHandler) ServeHTTP (w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "World!")
}
func main() {
  hello := HelloHandler{}
  world := WorldHandler{}
  server := http.Server{
    Addr: "127.0.0.1:8080",
  }
  http.Handle("/hello", &hello)
  http.Handle("/world", &world)
  server.ListenAndServe()
}

results matching ""

    No results matching ""